package com.robotic.minio;

import lombok.extern.slf4j.Slf4j;
import org.bytedeco.javacv.FFmpegFrameGrabber;
import org.bytedeco.javacv.Frame;
import org.bytedeco.javacv.Java2DFrameConverter;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;

@Component
@Slf4j
public class RTSPFrameCaptureWithJavaCV {

    private static final String rtspStreamUrl = "rtsp://10.110.7.219:554/ch01.264";
    /**
     * 使用JavaCV从RTSP流中截取一帧，并将其作为MultipartFile对象返回。
     * @return 包含图片数据的MultipartFile对象，如果失败则返回null。
     */
    public MultipartFile captureFrameAsMultipartFile() {
        // 使用try-with-resources确保资源被正确关闭
        try (FFmpegFrameGrabber grabber = new FFmpegFrameGrabber(rtspStreamUrl)) {
            grabber.setOption("rtsp_transport", "tcp");
            grabber.setOption("stimeout", "5000000"); // 5秒连接超时

            log.info("正在连接到RTSP流: " + rtspStreamUrl);
            grabber.start();
            log.info("连接成功，正在抓取帧...");

            Frame frame = grabber.grabImage();
            if (frame != null && frame.image != null) {
                // 1. 将抓取的帧转换为Java的BufferedImage
                Java2DFrameConverter converter = new Java2DFrameConverter();
                BufferedImage bufferedImage = converter.getBufferedImage(frame);

                // 2. 将BufferedImage转换为字节数组 (在内存中操作)
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                ImageIO.write(bufferedImage, "jpg", baos);
                byte[] imageBytes = baos.toByteArray();

                // 3. 生成文件名等元数据
                String timestamp = new SimpleDateFormat("yyyyMMdd_HHmmss_SSS").format(new Date());
                String fileName = "capture_" + timestamp + ".jpg";

                log.info("截图成功！已在内存中生成图片: " + fileName);

                // 4. 使用自定义实现类将字节数组包装成MultipartFile对象并返回
                return new InMemoryMultipartFile(imageBytes, "file", fileName, "image/jpeg");
            } else {
                log.error("抓取帧失败，未能获取到图像。");
                return null;
            }
        } catch (Exception e) {
            log.error("处理RTSP流时发生异常: " + e.getMessage());
            return null;
        }
    }

}
